using Cysharp.Threading.Tasks;
using IQIGame.Onigao.Game;

namespace IQIGame.Onigao.GamePlay
{
    public class MainCityController : TController
    {
        public MainCityRegionCtrl regionCtrl;
        public IConditionPropFetcher playerData;

        /// <summary>
        /// 主城常驻资源管理器，注意常驻资源生命周期必须贯穿整个主城，而不是某一个区域
        /// </summary>
        public MainCityPermanentResource permanentResource { get; private set; }
        public bool isSceneReady => regionCtrl != null && regionCtrl.isSceneReady;

        public MainCityController()
        {
            ManagerCenter.MonoDriver.updateEvent += Update;
        }

        public async UniTask Enter(int regionCid)
        {
            permanentResource = new MainCityPermanentResource();
            await permanentResource.LoadResource();
            await EnterRegion(regionCid);
        }

        public async UniTask SwitchRegion(int regionCid)
        {
            LeaveRegion();
            await EnterRegion(regionCid);
        }

        private async UniTask EnterRegion(int regionCid)
        {
            regionCtrl = AddSubController<MainCityRegionCtrl>();
            DispatchInnerEvent(TControllerEvent.OnModuleGameplayInit);
            await regionCtrl.Enter(regionCid);
        }

        private void LeaveRegion()
        {
            if (regionCtrl != null)
            {
                regionCtrl.Dispose();
                regionCtrl = null;
            }
        }

        private void Update(float deltaTime, float unscaledDeltaTime)
        {
            this.Update(deltaTime);
        }

        protected override void OnDispose()
        {
            ManagerCenter.MonoDriver.updateEvent -= Update;
            //LeaveRegion();不需要，主城的regionCtrl是子Controller，会自动销毁
            permanentResource?.Dispose();
            permanentResource = null;
        }
    }
}
